import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { BASE_URL, JWT_LS } from '../constants'
import { IProject } from '../model/interfaces'

export const getTokenFromLocalStorage = () => {
    return localStorage.getItem(JWT_LS)
}

export const projectsApi = createApi({
    reducerPath: 'projectsApi',
    baseQuery: fetchBaseQuery(
        { baseUrl: `${BASE_URL}/project`, headers: {Authorization: `Bearer ${getTokenFromLocalStorage()}`}  }),

    tagTypes:['Projects'],
    endpoints: (builder) => ({
        getProjects: builder.query<IProject[], void>({
            query: () => '',
            providesTags:['Projects']
        }),
        createProjects: builder.mutation<void, IProject>({
            query: (project: IProject) =>  ({
                method: 'POST',
                url: '',
                body: project
            }),
            invalidatesTags: ['Projects']
        }),
        updateProject: builder.mutation<void, IProject>({
            query: (project: IProject)=> ({
                method: 'PUT',
                url: `/${project._id}`,
                body: project
            }),
            invalidatesTags: ['Projects']
        }),
        deleteProject: builder.mutation<void, string>({
            query: (id: string) => ({
                method: 'DELETE',
                url: `/${id}`
            }),
            invalidatesTags: ['Projects']
        })
    }),
})

export const {
    useGetProjectsQuery,
  useLazyGetProjectsQuery,
  useCreateProjectsMutation,
  useUpdateProjectMutation,
  useDeleteProjectMutation,
} = projectsApi
